--[[
	撤销赠送
]]
local filename = "cancelgivemoney.lua"
local cluster = require "skynet.cluster"
local skynet = require "skynet"
local queue = require "skynet.queue"
local filelog = require "filelog"
require "pubenum"

local redisdao = require "redisdao"
local timetool = require "timetool"
local json = require "cjson.safe"
json.encode_sparse_array(true,1,1)

local service = nil
local CMD = {
	service = nil
}

local cs = queue()

--
--撤销赠送
--
local function cancelgivemoney(rid, msgbody)
	local keyid = tostring(msgbody.keyid)
	local charge_type = EDiamondChange.GIVEMONEY_RETURN
	local newstate = EGiveMoneySate.EGIVEMONEY_STATE_HAD_UNDO
	
	--修改状态
	local result = skynet.call(".givesystem", "lua", "update_givemoney_state", keyid, newstate)
	if not result or result.retcode then
		return result or {retcode = EErrCode.ERR_INVALID_REQUEST, retstr = "撤销失败"}
	end
	
	--修改金额
	local value = tonumber(result.give_value)
	service:charge_diamond(value, {change_type = charge_type, tradeid = result.tradeid}, "give")
	
	--修改今日赠送额度
	local curtime = timetool.get_time()
	local record_time = tonumber(result.create_time) or 0
	if record_time > 0 then
	 	local curday = os.date("%d", curtime)
		local lastday = os.date("%d", record_time)
		if lastday == curday and (curtime - record_time) < 86400 then
			local keyname = (rid or 0) .. ":givemoneyrecord"
			local _,record_data = redisdao.query_data(".gmmqredis", "get", keyname)
			local givemoneyrecord = json.decode(record_data or "{}") or { }
			givemoneyrecord.total_value = tonumber(givemoneyrecord.total_value) or 0
			if givemoneyrecord.total_value > value then
				givemoneyrecord.record_time = curtime
				givemoneyrecord.total_value = givemoneyrecord.total_value - value
				redisdao.query_data(".gmmqredis", "set", keyname, json.encode(givemoneyrecord))
			end
		end
	end
	
	return {}
end

-- 处理玩家撤销赠送
function CMD.process(rid, msgbody)
	if not service then
		service = CMD.service
	end
	
	return cs(cancelgivemoney, rid, msgbody)
end

return CMD
